﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CorpStoreServer
{
    public class AppSettings
    {
        public string CommonCatalogFn { get; set; }
        public string LastCatalogChecksum { get; set; }

        private string _settingsFn;
        private string _errStr;

        public string lastErrStr()
        {
            return _errStr;
        }

        public bool Init(string settingsFn, Log log)
        {
            bool blnOK = false;

            _errStr = "";
            try
            {
                _settingsFn = settingsFn;
                if (!System.IO.File.Exists(settingsFn))
                {
                    // settings file does not exist yet - create a default one
                    CommonCatalogFn = string.Format(@"{0}\CommonCatalog.json", GenLib.AppExePath());
                    log.LogInfo("AppSettings file '{0}' does not exist.  Attempting to create it with default commonCatalogFn={1}", settingsFn, CommonCatalogFn);
                    LastCatalogChecksum = "";

                    if (Save())
                        log.LogInfo("Saved new app settings file OK");
                    else
                        log.LogErr("Error saving new app settings file");
                }

                log.LogInfo("Attempting to read appSettings file '{0}'", _settingsFn);
                string rawData = System.IO.File.ReadAllText(_settingsFn);
                log.LogInfo("Attempting to deserialize json read from appSettings file");
                AppSettings currSettings = JsonConvert.DeserializeObject<AppSettings>(rawData);

                CommonCatalogFn = currSettings.CommonCatalogFn;
                LastCatalogChecksum = currSettings.LastCatalogChecksum;

                log.LogInfo("CommonCatalogFn read from appSettings file '{0}' is '{1}'", _settingsFn, CommonCatalogFn);
                blnOK = true;
            }
            catch (Exception ex)
            {
                _errStr = string.Format("Unhandled exception while initializing appSettings from file '{0}' : {1}", settingsFn, ex.Message);
            }

            return blnOK;
        }


        public bool Save()
        {
            bool blnOK = false;

            _errStr = "";
            try
            {
                System.IO.File.WriteAllText(_settingsFn, JsonConvert.SerializeObject(this, Formatting.Indented));
                blnOK = true;
            }
            catch (Exception ex)
            {
                _errStr = string.Format("Unhandled exception in AppSettings.Save: {0}", ex.Message);
            }

            return blnOK;
        }


    }
}
